package com.securite.security.config;

import com.securite.security.handler.MyAuthenticationFailureHandler;
import com.securite.security.handler.MyAuthenticationSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Description: TODO(配置类)
 * @Author da
 * @Date 2021/10/24 上午 10:54
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
{

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.formLogin()
                //    自定义登陆页面
                .loginPage("/login.html")
//                执行登陆逻辑
                .loginProcessingUrl("/login")
//                自定义入参(input的name值,默认是username,password)
                .usernameParameter("aa")
                .passwordParameter("bb")
//                登陆成功后跳转的页面(POST请求)
//                .successForwardUrl("/toMain")
//                使用自定义的登陆成功处理器
                .successHandler(new MyAuthenticationSuccessHandler("https://da9527.gitee.io"))
//                登陆失败后跳转的页面(POST请求)
//                .failureForwardUrl("/toError")
//                使用自定义的登陆失败处理器
                .failureHandler(new MyAuthenticationFailureHandler("https://da9527.gitee.io"));

//        关闭csrf防御,不然没有效果
        http.csrf().disable();

//        授权
        http.authorizeRequests()
//                放行/login.html,不需要认证
                .antMatchers("/login.html").permitAll()
//                放行错误页面
                .antMatchers("/error.html").permitAll()
//                放行静态资源
                .antMatchers("/css/**", "/js/**", "image/**").permitAll()
//                所有请求必须授权(登陆)才能访问
                .anyRequest().authenticated();
    }

    @Bean
    public PasswordEncoder getPw()
    {
        return new BCryptPasswordEncoder();
    }
}
